using HCore.IOC.Context.Event.Attr;
using HCore.Unity.Behaviour;
using HCore.Unity.Core;
using HCore.Unity.Extensions;
using JetBrains.Annotations;
using UI.UIGame.Cursor.Event;
using UnityEngine;
using UnityEngine.UI;

namespace UI.UIGame.Cursor
{
    public class CursorVisual : HCoreMonoBehaviour
    {
        /// <summary>
        ///     为了「优化性能」，间隔获取一次鼠标位置，计算所在格子坐标。
        /// </summary>
        [SerializeField] [Range(1, 24)] public int FrameGap = 3;

        private Image mImage; // 建造对象的精灵渲染器

        protected override void Awake()
        {
            base.Awake();
            mImage = Get("Icon").Image;
        }

        private void Start()
        {
            transform.ResetLocalPosition();
            mImage.enabled = false;
        }

        private void Update()
        {
            // 游戏暂停
            // if (FunctionBehaviour.Instance.PauseUpdate) return;

            // 间隔获取一次鼠标位置，计算所在格子坐标。「优化性能」
            if (Time.frameCount % FrameGap != 0) return;

            // 设置格子的鼠标选择框坐标
            transform.localPosition = GameUtils.GetUILocalPointPositionFromScreen(transform.parent);
        }

        [UsedImplicitly]
        [EventListener]
        private void OnShowCursorIconEvent(ShowCursorIconEvent showCursorIconEvent)
        {
            var sprite = showCursorIconEvent.Sprite;
            var color = showCursorIconEvent.Color;

            if (sprite)
            {
                mImage.sprite = sprite;
                if (color.HasValue) mImage.color = color.Value;
                mImage.enabled = true;
            }
            else
            {
                mImage.enabled = false;
                mImage.sprite = null;
                mImage.color = Color.white;
            }
        }
    }
}